package com.qiku.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.qiku.reggie.common.BaseContext;
import com.qiku.reggie.common.R;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter("/*")
@Slf4j
public class CheckLoginFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1 判断请求路径是否需要拦截
        String requestURI = request.getRequestURI();

        String[] urls = {
                "/backend/**" , "/font/**" ,    "/employee/login"
        };
        boolean flag = check(urls , requestURI);

        if (flag){
            // 放行资源
            filterChain.doFilter(request , response);
            return; // 必须加return
        }


        // 2 判断用户是否登录
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null){
            // 将用户id存入当前线程
            BaseContext.setCurrentId(empId);
            // 输出当前线程的ID
//            log.info("当前线程的Id=" + Thread.currentThread().getId());
            // 用户已经登录
            filterChain.doFilter(request , response);
            return;
        }

        // 3 用户未登录  响应 code = 0 && msg = NOTLOGIN
        log.info("用户未登录");
        String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(jsonString);



    }

    private boolean check(String[] urls, String requestURI) {

        // 路径匹配器
        AntPathMatcher pathMatcher = new AntPathMatcher();
        // 遍历数组中的路径表达式
        for (String url : urls) {
            boolean match = pathMatcher.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;

    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }



    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
